package com.kangzhan.filter;

import com.alibaba.fastjson.JSON;
import com.kangzhan.utils.Constants;
import com.kangzhan.utils.RedisUtil;
import com.kangzhan.utils.ReturnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "MyFilter", urlPatterns = "/*")
public class MyFilter implements Filter {

    @Resource
    private RedisUtil redisUtil;

    //定义那些不需要被拦截的请求，比如登录或者静态资源
    protected static String[] authorizedUrls = new String[] {"/**/user/login",
             "/**/jsp/**","/**/statics/**"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       // 将它转换为HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // 进行utf-8编码。 可以不加这句代码，因为我们已经在web.xml中配置了一个编码过滤器
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/javascript");
        // 从请求头 获取token
        String token = req.getHeader(Constants.TOKEN_ID);
        // 从req中获取此次请求的 路径
        String url = req.getRequestURI();
        // 判断当前路径是不是需要放行
        for (String authorizedUrl : authorizedUrls) {
            // matcher 对象可以使用match方法进行 通配符的匹配
            PathMatcher matcher = new AntPathMatcher();
            if(matcher.match(authorizedUrl,url)){
                // 放行
                filterChain.doFilter(req, resp);
            }
        }
        // 判断是否存在token
        if(token==null||"".equals(token)){
            //token为空，说明用户没登录
            String returnStr = JSON.toJSONString(ReturnUtil.fail(400, "用户未登录"));
            resp.getWriter().write(returnStr);
            return;
        }
        //对token进行真实性校验
        // 通过redis.get(key)的方式，判断是否有这个token
        Object tmpUser = redisUtil.get(token);

        Map map = (Map<String, Object>) tmpUser;

        if(tmpUser!=null){
            //req.setAttribute("userId",map.get("userId"));
            // 需要将token的过期时间重置
           // redisUtil.expire(token, 3600);
            filterChain.doFilter(req, resp);
        }else{
            // 不存在这个token,说明登录过期或者是非法的token
            String returnStr = JSON.toJSONString(ReturnUtil.fail(401, "非法登录"));
            resp.getWriter().write(returnStr);
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
